package com.scaffold.myproject.common;

import lombok.Getter;

import java.io.Serializable;
import java.util.function.Consumer;

/**
 * 返回结果统一格式
 *
 * @param <T>
 */
public class Result<T> implements Serializable {

    @Getter
    private final int code;
    @Getter
    private final boolean error;
    @Getter
    private String message;
    @Getter
    private T data;
    @Getter
    private String exceptionId;


    private Result() {
        this(0);
    }

    private Result(int code) {
        this(code, null);
    }

    private Result(int code, String message) {
        this.code = code;
        this.message = message;
        this.error = this.code > 0;
    }

    private Result(int code, boolean error, String exceptionId, String message) {
        this.code = code;
        this.message = message;
        this.error = error;
        this.exceptionId = exceptionId;
    }

    @SuppressWarnings("unchecked")
    public static <T> Result<T> of(T data) {
        return new Result<>().data(data);
    }

    public static <T> Result<T> of() {
        return new Result<>();
    }

    @SuppressWarnings("unchecked")
    public static <T> Result<T> of(int code, T data) {
        return new Result<>(code).data(data);
    }

    public static <T> Result<T> code(int code) {
        return new Result<>(code);
    }

    @SuppressWarnings("rawtypes")
    public void to(Consumer<Result> action) {
        action.accept(this);
    }


    public static <T> Result<T> error(int code, String exceptionId, String message) {
        return new Result<>(code, true, exceptionId, message);
    }

    public static <T> Result<T> error(int code, String message) {
        return new Result<>(code, true, null, message);
    }

    @SuppressWarnings("rawtypes")
    public Result message(String message) {
        this.message = message;
        return this;
    }

    @SuppressWarnings("rawtypes")
    public Result data(T data) {
        this.data = data;
        return this;
    }
}